package com.huanzhidadi.rabbitmq.controller;

import com.huanzhidadi.rabbitmq.cache.MyCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Api(tags = "订单付款延迟队列模拟")
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @ApiOperation(value = "订单创建", notes = "订单创建")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void add(@RequestParam String orderId, @RequestParam Boolean payFlag) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"));
        log.info("订单 {} 创建成功：{}", orderId, dateFormat.format(new Date()));

        // 发送消息到订单延迟队列
        amqpTemplate.convertAndSend("order_delayed_exchange", "order_delay_queue", orderId, message -> {
            // 消息延迟5s
            message.getMessageProperties().setDelay(5000);
            return message;
        });

        try {
            Thread.sleep(2000L);
            // 经过一段时间，把支付状态存储起来
            MyCache.orderPayMap.put(orderId, payFlag);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
